package com.edie.customview.data.net;

import com.edie.customview.BuildConfig;
import com.edie.customview.util.MD5;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.Response;

/**
 * edie create on 2018/7/16
 */
public class CommonInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        //获取到request
        Request request = chain.request();
        //获取到方法
        String method = request.method();


        //get请求
        if (method.equals("GET")) {
            //添加公共参数
            HttpUrl httpUrl = request.url()
                    .newBuilder()
                    //根据需要添加自己的公共参数
                    .addQueryParameter("clienttype", "1")
                    .addQueryParameter("imei", "imei")
                    .addQueryParameter("version", "VersionName")
                    .addQueryParameter("timestamp", String.valueOf(System.currentTimeMillis()))
                    .build();

            request = request.newBuilder()
                    .url(httpUrl)
                    .build();
        } else if (method.equals("POST")) {
            //post请求的封装

            if (request.body() instanceof FormBody) {
                //新建Builder
                FormBody.Builder bodyBuilder = new FormBody.Builder();
                FormBody formBody = (FormBody) request.body();

                //这里主要是为了计算hashid
                Map<String, String> maps = new HashMap<>();
                maps.put("device", "android");
                maps.put("deviceid", "abcde123f");
                String time = String.valueOf(System.currentTimeMillis() / 1000);
                maps.put("time", time);
                maps.put("version", BuildConfig.VERSION_NAME);

                //把原来的参数添加到新的构造器
                for (int i = 0; i < formBody.size(); i++) {
                    //把原来的参数添加到新的构造器
                    bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i));
                    //把原来的参数添加map集合
                    maps.put(formBody.encodedName(i), formBody.encodedValue(i));
                }

                List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(maps.entrySet());
                Collections.sort(list, (o1, o2) -> o1.getKey().compareTo(o2.getKey()));
                String hash = getHash(list);

                formBody = bodyBuilder
                        //根据需要添加自己的公共参数
                        .addEncoded("device", "android")
                        .addEncoded("deviceid", "abcde123f")
                        .addEncoded("time", time)
                        .addEncoded("version", BuildConfig.VERSION_NAME)
                        .addEncoded("hash", hash)
                        .build();

                request = request.newBuilder()
                        .post(formBody)
                        .build();
            } else if (request.body() instanceof MultipartBody) {
                MultipartBody.Builder multipartBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);

                //添加原来的参数
                List<MultipartBody.Part> oldParts = ((MultipartBody) request.body()).parts();
                if (oldParts != null && oldParts.size() > 0) {
                    for (MultipartBody.Part part : oldParts) {
                        multipartBuilder.addPart(part);
                    }
                }

                //添加公共参数

                //假的
//                Iterator iterator = paramsMap.entrySet().iterator();
//                while (iterator.hasNext()) {
//                    Map.Entry entry = (Map.Entry) iterator.next();
//                    multipartBuilder.addFormDataPart((String) entry.getKey(), (String) entry.getValue());
//                }


                request = request.newBuilder()
                        .post(multipartBuilder.build())
                        .build();
            }

        }
        //最后通过chain.proceed(request)进行返回
        return chain.proceed(request);

    }

    /**
     * 计算hashid值
     * @param values
     * @return
     */
    public String getHash(List<Map.Entry<String, String>> values) {
        String securityCode = "8cUoeQ31Q3C+5DQEDkYD55RA++GP0EwJgE95gaxbZlo=";
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : values) {
            sb.append(entry.getValue());
        }
        sb.append(securityCode);
        return MD5.getStringMD5(sb.toString());
    }

}
